import abc

class CardReader(metaclass=abc.ABCMeta):
    #初始化方法
    def __init__(self, e_mode):
        self.port = None
        #False：不加密，True:加密
        self.e_mode = e_mode
    #发送命令
    def send_cmd(self, cmd):
        print('Command:', cmd)
        if self.open():
            data = self.encrypt(cmd)
            self.write(data)
            self.close()
    #获得应答
    def read_response(self):
        if self.open():
            data = self.read()
            self.close()
            return self.decrypt(data)
        else:
            return None

    #加密映射表
    code_dict = {
    'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e', 'e': 'f', 'f':
    'g', 'g': 'h',
    'h': 'i', 'i': 'j', 'j': 'k', 'k': 'l', 'l': 'm', 'm':
    'n', 'n': 'o',
    'o': 'u', 'p': 't', 'q': 's', 'r': 'r', 's': 'q', 't': 'p',
    'u': 'v', 'v': 'y', 'w': 'a', 'x': 'z', 'y': 'x', 'z': 'w',
    '[': '#', ']': '$', ' ': '?', '.': '2'
    }
    #加密
    def encrypt(self, data):
        if self.e_mode:
            ret = ''
            for c in data:
                ret = ret + self.code_dict[c]
            return ret
        else:
            return data
    # 解密
    def decrypt(self, data):
        if self.e_mode:
            ret = ''
            for c in data:
                for key, w in self.code_dict.items():
                    if c == w:
                        ret = ret + key
            return ret
        else:
            return data

    @abc.abstractmethod
    def open(self):
        pass
    @abc.abstractmethod
    def close(self):
        pass
    @abc.abstractmethod
    def write(self, data):
        pass
    @abc.abstractmethod
    def read(self):
        pass


class TestCardReader(CardReader):
    def __init__(self, port_id, e_mode):
        CardReader.__init__(self, e_mode)
        self.port_id = port_id
    def open(self):
        print('Open usb port:', self.port_id)
        return True
    def close(self):
        print('Close usb port:', self.port_id)
        return True
    def write(self, data):
        print('write(',self.port_id, ',', data, ')')
    def read(self):
        ret = "tbqqaure?dibohfe?qvddfqgvmmx2"
        print('read(', self.port_id, ',', ret, ')')
        return ret

if __name__ == '__main__':
    reader = TestCardReader("Test", True)
    print('>>>>>>>>send command test.>>>>>>>>>>')
    reader.send_cmd("change password from [byebye] to [hello].")
    print('>>>>>>>>read command test.>>>>>>>>>>')
    print('Response:', reader.read_response())